<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <div class="filter-wrapper">
      <NewPageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
        :filter-btn="filterInfo.btn"
      >
        <template v-slot:filter-operateTime>
          <el-date-picker
            v-model="operateTime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            align="right"
            start-placeholder="操作时间开始日期"
            end-placeholder="操作时间结束日期"
            :clearable="false"
            @change="timeChange"
          ></el-date-picker>
        </template>
      </NewPageFilter>
    </div>
    <div class="filter-wrapper">
      <NewPageFilter
        :filter-list="filterInfo.btnList"
        :filter-btn="filterInfo.btnList"
      >
        <template v-slot:filter-sortBtn>
          <Sorts @sort="sort"></Sorts>
        </template>
      </NewPageFilter>
    </div>
    <!-- 表格 -->
    <TableContainer
      ref="tableRef"
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :query="filterInfo.query"
      :tab-index="true"
      :field-list="tableInfo.fieldList"
      :pager="true"
      :checkBox="true"
      :handle="tableInfo.handle"
      @handleEvent="handleEvent"
    >
      <template v-slot:col-title="scope">
        <span class="slip-edit" @click="showDetail(scope.row)">{{
          scope.row.title
        }}</span>
      </template>
    </TableContainer>
    <!-- S 发布弹窗 -->
    <PublishDialog
      :fileList="fileList"
      :open="publishOpen"
      @submit="submit"
      @close="publishClose"
    ></PublishDialog>
    <!-- E 发布弹窗 -->
  </div>
</template>

<script setup name="publishFile">
import PublishDialog from './publishDialog.vue'
import Sorts from './sorts.vue'
import moment from 'moment'
import {
  getPublishListPage,
  publishFile,
  publishVoidFile,
  getPersons,
  cancelFile,
  cancelVoidFile,
} from '@/api/fileManager'
import { deepClone } from '@/utils'

const { proxy } = getCurrentInstance()
const router = useRouter()

let publishOpen = ref(false)
const fileList = ref([])
const operateTime = ref([
  moment(new Date(new Date().getTime() - 3600 * 1000 * 24 * 30)).format(
    'YYYY-MM-DD'
  ),
  moment(new Date()).format('YYYY-MM-DD'),
])
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: getPublishListPage,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '文档目录',
      value: 'categoryName',
    },
    {
      label: '文档名称',
      value: 'title',
      type: 'slot',
    },
    {
      label: '文档编码',
      value: 'fileCode',
    },
    {
      label: '版本号',
      value: 'version',
    },
    {
      label: '发布人',
      value: 'publishUser',
    },
    {
      label: '发布时间',
      value: 'publishDate',
    },
    {
      label: '状态',
      value: 'statusText',
    },
    {
      label: '阅读',
      value: 'readNum',
    },
    {
      label: '下载',
      value: 'downloadNum',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    btList: [
      {
        label: '发布',
        event: publish,
        show: proxy.$permission('publishFile:publish'),
        ifRender: function (item) {
          if (item.status === 'PEND_PUBLISH') {
            return true
          }
          return false
        },
      },
      {
        label: '取消发布',
        event: submitVoidFileFun,
        show: proxy.$permission('publishFile:unpublish'),
        ifRender: function (item) {
          if (item.status === 'PUBLISH') {
            return true
          }
          return false
        },
      },
      {
        label: '作废',
        event: cancelFileFun,
        show: proxy.$permission('publishFile:del'),
        ifRender: function (item) {
          if (item.status === 'PEND_PUBLISH') {
            return true
          }
          return false
        },
      },
      /* {
        label: '恢复',
        event: cancelVoidFileFun,
        show: proxy.$permission('publishFile:undel'),
        ifRender: function (item) {
          if (item.status === 'CANCEL') {
            return true
          }
          return false
        },
      }, */
    ],
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    startDate: operateTime.value[0],
    endDate: operateTime.value[1],
    orderDirect: 'desc',
    orderBy: 'sfd.create_time',
  },
  copyQuery: {},
  list: [
    {
      componentType: 'input',
      label: '文档编码/文档名称',
      value: 'searchValue',
      event: search,
    },
    {
      slot: true,
      label: '起止日期',
      value: 'operateTime',
      event: search,
    },
  ],
  btn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      slot: true,
      label: '',
      value: 'sortBtn',
    },
    {
      type: 'button',
      label: '发布',
      key: 'publish',
      disabled: true,
      event: publishHead,
      show: proxy.$permission('publishFile:publish'),
    },
  ],
})

const selectionsLen = computed(() => {
  return tableInfo.value.selections.length
})
watch(
  () => tableInfo.value.selections,
  (val) => {
    let pendPublishArr = val.filter((element) => {
      return element.status === 'PEND_PUBLISH'
    })
    if (pendPublishArr.length && pendPublishArr.length === val.length) {
      setPublishBtn(false)
    } else {
      setPublishBtn(true)
    }
  },
  { deep: true }
)

function setPublishBtn(status) {
  filterInfo.value.btnList.forEach((element, index) => {
    if (element.key === 'publish') {
      filterInfo.value.btnList[index].disabled = status
    }
  })
}
onMounted(() => {
  filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query)
})

function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.startDate = val[0]
    filterInfo.value.query.endDate = val[1]
  } else {
    filterInfo.value.query.startDate = ''
    filterInfo.value.query.endDate = ''
  }
  search()
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQuery)
  operateTime.value = [
    filterInfo.value.query.startDate,
    filterInfo.value.query.endDate,
  ]
  search()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function sort(val) {
  filterInfo.value.query.orderBy = val.orderBy
  filterInfo.value.query.orderDirect = val.orderDirect
  if (!val.orderBy && !val.orderDirect) {
    filterInfo.value.query.orderBy = 'sfd.create_time'
    filterInfo.value.query.orderDirect = 'desc'
  }
  getList()
}
function showDetail(row) {
  proxy.$router.push({
    path: '/fileManager/fileview/' + row.id,
    query: {
      view: 1,
      active: '/fileManager/cancellation',
    },
  })
}

function publishClose() {
  fileList.value = []
  tableInfo.value.selections.forEach((element) => {
    proxy.$refs.tableRef.toggleRowSelection(element, false)
  })
  publishOpen.value = false
}
function cancelFileFun(row) {
  proxy
    .$confirm('是否确认作废本条数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      cancelFile([row.id]).then((res) => {
        if (res.success) {
          getList()
          showTip()
        }
      })
    })
}
function cancelVoidFileFun(row) {
  proxy
    .$confirm('是否确认恢复本条数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      cancelVoidFile([row.id]).then((res) => {
        if (res.success) {
          getList()
          showTip()
        }
      })
    })
}
function submit() {
  let fileArr = []
  fileList.value.forEach((element) => {
    let params = {
      allowView: element.allowView ? element.allowView : '0',
      allowUpload: element.allowUpload ? element.allowUpload : '0',
      allowDownloads: element.allowDownloads ? element.allowDownloads : '0',
      allowPreview: element.allowPreview ? element.allowPreview : '0',
      allowPrint: element.allowPrint ? element.allowPrint : '0',
      // allowDeleted: element.allowDeleted ? element.allowDeleted : '0',
      categoryName: element.categoryName,
      fileName: element.title,
      id: element.id,
    }
    fileArr.push(params)
  })
  publishFile({ sysFileInfos: fileArr }).then((res) => {
    if (res.code === 200 && res.success) {
      getList()
      publishOpen.value = false
      showTip()
    }
  })
}
function submitVoidFileFun(row) {
  proxy
    .$confirm('是否确认取消发布本条数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      publishVoidFile([row.id]).then((res) => {
        if (res.success) {
          getList()
          showTip()
        }
      })
    })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function handleSelectionChange(data) {
  fileList.value = deepClone(data)
}
function publishHead() {
  if (selectionsLen.value === 0) {
    proxy.$message.warning('请至少选择一条数据')
    return
  }
  fileList.value = deepClone(tableInfo.value.selections)
  publish(tableInfo.value.selections)
  //publishOpen.value = true
}
function publish(row) {
  fileList.value = deepClone([row])
  proxy
    .$confirm('是否确认发布选择数据？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let fileArr = []
      let params = {}
      if (row.length) {
        row.forEach((element) => {
          params = {
            categoryName: element.categoryName,
            fileName: element.title,
            id: element.id,
          }
          fileArr.push(params)
        })
      } else {
        params = {
          categoryName: row.categoryName,
          fileName: row.title,
          id: row.id,
        }
      }
      fileArr.push(params)
      publishFile({ sysFileInfos: fileArr }).then((res) => {
        if (res.code === 200 && res.success) {
          getList()
          showTip()
          publishOpen.value = false
        }
      })
    })
  //publishOpen.value = true
}
function showTip() {
  proxy.$message.success({
    message: '操作成功',
    showClose: true,
    duration: 3500,
  })
}
function showDetails(obj) {
  let _obj = obj
  if (_obj.val) {
    _obj = _obj.val
  }
  router.push({
    path: '/fileManager/fileview/' + _obj.id,
    query: {
      view: 1,
      active: '/fileManager/publish',
    },
  })
}
//删除
function del(row = undefined) {
  const ids = _getIds(row)
  deleteAssetAnalysis(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
</script>
